import React, { useRef, useState } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, Space, Tag, Popconfirm, message, Modal, Dropdown, Typography, Badge } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, MoreOutlined, SoundOutlined, ExportOutlined, ImportOutlined } from '@ant-design/icons';
import { getDetectionTextList, deleteDetectionText, updateDetectionTextStatus, generatePinyin, batchImportTexts } from '@/services/learningContentApi';
import DetectionTextForm from './components/DetectionTextForm';
import AudioPlayer from './components/AudioPlayer';
import ImportModal from './components/ImportModal';

const { Text } = Typography;

const DetectionTextList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [textFormVisible, setTextFormVisible] = useState(false);
  const [importModalVisible, setImportModalVisible] = useState(false);
  const [currentText, setCurrentText] = useState<LEARNING.DetectionTextModel | undefined>();
  const [editMode, setEditMode] = useState<'create' | 'edit'>('create');
  const [audioPlayerVisible, setAudioPlayerVisible] = useState(false);

  // 状态标签颜色映射
  const statusColorMap = {
    active: 'green',
    inactive: 'orange',
  };

  // 难度标签颜色映射
  const difficultyColorMap = {
    easy: 'green',
    medium: 'orange',
    hard: 'red',
  };

  // 表格列定义
  const columns: ProColumns<LEARNING.DetectionTextModel>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 60,
      search: false,
    },
    {
      title: '文本内容',
      dataIndex: 'content',
      width: 300,
      ellipsis: true,
      copyable: true,
      render: (text) => (
        <Text style={{ maxWidth: 280 }} ellipsis={{ tooltip: text }}>
          {text}
        </Text>
      ),
    },
    {
      title: '拼音',
      dataIndex: 'pinyin',
      width: 200,
      search: false,
      ellipsis: true,
      render: (pinyin, record) => (
        <div>
          {pinyin ? (
            <Text type="secondary" style={{ fontSize: '12px' }}>
              {pinyin}
            </Text>
          ) : (
            <Button
              type="link"
              size="small"
              onClick={() => handleGeneratePinyin(record)}
            >
              生成拼音
            </Button>
          )}
        </div>
      ),
    },
    {
      title: '难度',
      dataIndex: 'difficulty',
      width: 100,
      valueType: 'select',
      valueEnum: {
        easy: { text: '简单', status: 'Success' },
        medium: { text: '中等', status: 'Warning' },
        hard: { text: '困难', status: 'Error' },
      },
      render: (_, record) => {
        const difficultyMap = { easy: '简单', medium: '中等', hard: '困难' };
        return (
          <Tag color={difficultyColorMap[record.difficulty]}>
            {difficultyMap[record.difficulty]}
          </Tag>
        );
      },
    },
    {
      title: '分类',
      dataIndex: 'category',
      width: 120,
      valueType: 'select',
      valueEnum: {
        daily: { text: '日常用语' },
        business: { text: '商务用语' },
        academic: { text: '学术用语' },
        poetry: { text: '诗词歌赋' },
        idiom: { text: '成语俗语' },
      },
    },
    {
      title: '音频',
      dataIndex: 'audio_url',
      width: 80,
      search: false,
      render: (audioUrl, record) => (
        audioUrl ? (
          <Button
            type="link"
            size="small"
            icon={<SoundOutlined />}
            onClick={() => handlePlayAudio(record)}
          >
            播放
          </Button>
        ) : (
          <Text type="secondary">无音频</Text>
        )
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      valueType: 'select',
      valueEnum: {
        active: { text: '启用', status: 'Success' },
        inactive: { text: '禁用', status: 'Warning' },
      },
      render: (_, record) => (
        <Tag color={statusColorMap[record.status]}>
          {record.status === 'active' ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '使用次数',
      dataIndex: 'usage_count',
      width: 100,
      search: false,
      render: (count) => (
        <Badge count={count || 0} showZero color="#52c41a" />
      ),
    },
    {
      title: '正确率',
      dataIndex: 'accuracy_rate',
      width: 100,
      search: false,
      render: (rate) => rate ? `${(rate * 100).toFixed(1)}%` : '-',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 160,
      search: false,
      valueType: 'dateTime',
      sorter: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 120,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="edit"
          type="link"
          size="small"
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>,
        <Dropdown
          key="more"
          menu={{
            items: [
              {
                key: 'pinyin',
                label: '生成拼音',
                onClick: () => handleGeneratePinyin(record),
              },
              {
                key: 'status',
                label: record.status === 'active' ? '禁用' : '启用',
                onClick: () => handleStatusChange(record),
              },
              {
                type: 'divider',
              },
              {
                key: 'delete',
                label: '删除',
                icon: <DeleteOutlined />,
                danger: true,
                onClick: () => handleDelete(record),
              },
            ],
          }}
        >
          <Button type="link" size="small">
            <MoreOutlined />
          </Button>
        </Dropdown>,
      ],
    },
  ];

  // 处理编辑
  const handleEdit = (record: LEARNING.DetectionTextModel) => {
    setCurrentText(record);
    setEditMode('edit');
    setTextFormVisible(true);
  };

  // 处理生成拼音
  const handleGeneratePinyin = async (record: LEARNING.DetectionTextModel) => {
    try {
      await generatePinyin(record.id);
      message.success('拼音生成成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('拼音生成失败');
    }
  };

  // 处理播放音频
  const handlePlayAudio = (record: LEARNING.DetectionTextModel) => {
    setCurrentText(record);
    setAudioPlayerVisible(true);
  };

  // 处理状态变更
  const handleStatusChange = (record: LEARNING.DetectionTextModel) => {
    const newStatus = record.status === 'active' ? 'inactive' : 'active';
    const actionText = newStatus === 'active' ? '启用' : '禁用';
    
    Modal.confirm({
      title: `确认${actionText}`,
      content: `确定要${actionText}文本 "${record.content.substring(0, 20)}..." 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await updateDetectionTextStatus(record.id, newStatus);
          message.success(`文本${actionText}成功`);
          actionRef.current?.reload();
        } catch (error) {
          message.error(`文本${actionText}失败`);
        }
      },
    });
  };

  // 处理删除
  const handleDelete = (record: LEARNING.DetectionTextModel) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除文本 "${record.content.substring(0, 20)}..." 吗？此操作不可恢复。`,
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          await deleteDetectionText(record.id);
          message.success('删除成功');
          actionRef.current?.reload();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理新建
  const handleCreate = () => {
    setCurrentText(undefined);
    setEditMode('create');
    setTextFormVisible(true);
  };

  // 处理批量生成拼音
  const handleBatchGeneratePinyin = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要生成拼音的文本');
      return;
    }

    Modal.confirm({
      title: '批量生成拼音',
      content: `确定要为选中的 ${selectedRowKeys.length} 个文本生成拼音吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await Promise.all(
            selectedRowKeys.map(id => generatePinyin(id))
          );
          message.success('批量生成拼音成功');
          setSelectedRowKeys([]);
          actionRef.current?.reload();
        } catch (error) {
          message.error('批量生成拼音失败');
        }
      },
    });
  };

  return (
    <PageContainer>
      <ProTable<LEARNING.DetectionTextModel>
        headerTitle="检测文本列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleCreate}
          >
            新建文本
          </Button>,
          <Button
            key="import"
            icon={<ImportOutlined />}
            onClick={() => setImportModalVisible(true)}
          >
            批量导入
          </Button>,
        ]}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        tableAlertOptionRender={() => (
          <Space size={16}>
            <a onClick={handleBatchGeneratePinyin}>批量生成拼音</a>
          </Space>
        )}
        request={async (params, sort) => {
          const response = await getDetectionTextList({
            page: params.current,
            limit: params.pageSize,
            content: params.content,
            difficulty: params.difficulty,
            category: params.category,
            status: params.status,
          });
          return {
            data: response.data.list,
            success: response.code === 200,
            total: response.data.pagination.total,
          };
        }}
        columns={columns}
        rowSelection={{
          selectedRowKeys,
          onChange: (keys) => setSelectedRowKeys(keys as number[]),
        }}
        scroll={{ x: 1400 }}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
      />

      {/* 文本表单弹窗 */}
      <DetectionTextForm
        visible={textFormVisible}
        mode={editMode}
        initialValues={currentText}
        onCancel={() => setTextFormVisible(false)}
        onSuccess={() => {
          setTextFormVisible(false);
          actionRef.current?.reload();
        }}
      />

      {/* 音频播放器弹窗 */}
      <AudioPlayer
        visible={audioPlayerVisible}
        text={currentText}
        onCancel={() => setAudioPlayerVisible(false)}
      />

      {/* 批量导入弹窗 */}
      <ImportModal
        visible={importModalVisible}
        onCancel={() => setImportModalVisible(false)}
        onSuccess={() => {
          setImportModalVisible(false);
          actionRef.current?.reload();
        }}
      />
    </PageContainer>
  );
};

export default DetectionTextList;
